package com.orion.service.impl;

import com.orion.dao.RoleDao;
import com.orion.dao.UserDao;
import com.orion.dao.UserRoleDao;
import com.orion.entity.Role;
import com.orion.entity.User;
import com.orion.entity.UserRole;
import com.orion.service.TransService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Administrator
 * @date 2021/12/1
 */
@Service("transService")
public class TransServiceImpl implements TransService {

    @Resource(name = "userDao")
    private UserDao userDao;

    @Resource(name = "roleDao")
    private RoleDao roleDao;

    @Resource(name = "userRoleDao")
    private UserRoleDao userRoleDao;

    /**
     * 保存user、role 以及其关系，测试事务
     *
     * @param user
     * @param role
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveUserRoleRela(User user, Role role) {
        int userEftCnt = userDao.insert(user);
        int roleEftCnt = roleDao.insert(role);
        int userRoleCnt = 0;
        if (userEftCnt > 0 && roleEftCnt > 0) {
            //int i = 1/0; 事务回滚
            UserRole userRole = new UserRole();
            userRole.setRoleId(role.getId());
            userRole.setUserId(user.getId());
            userRoleCnt = userRoleDao.insert(userRole);
        }
        return userRoleCnt > 0;
    }

}
